package com.roamer.javase.demo.export.vo;

import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 多部分数据 pro
 *
 * @author roamer
 * @version v1.0
 * @date 2020/5/5 17:25
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class MultipartRowModel extends ExportModel {
    private static final long serialVersionUID = -2799134454672708920L;

    private List<ExportModel> exportModels;

    public MultipartRowModel(List<ExportModel> exportModels) {
        assert exportModels != null && !exportModels.isEmpty();
        this.exportModels = exportModels;
    }

    @Override
    public List<Map<String, Object>> getDataMapList() {
        return exportModels.stream().flatMap(e -> e.getDataMapList().stream()).collect(Collectors.toList());
    }

    @Override
    public List<int[]> getMergedRegion() {
        List<int[]> list = new ArrayList<>();
        // 计算总行数
        int sum = Math.max(exportModels.get(0).getDataMapList().size() + 2 - 1, 2);
        sum += exportModels.stream().skip(1).mapToInt(e -> e.getDataMapList().size()).sum();

        int start = 0;
        for (int i = 0; i < exportModels.size(); i++) {
            ExportModel exportModel = exportModels.get(i);
            for (int j = 0; j < exportModel.getMergedRegion().size(); j++) {
                int[] regions = exportModel.getMergedRegion().get(j);
                if (i == 0) {
                    if (regions[4] == 0) {
                        list.add(new int[]{regions[0], regions[1], regions[2], regions[3]});
                        start = regions[1];
                    } else {
                        list.add(new int[]{regions[0], sum, regions[2], regions[3]});
                    }
                } else if (exportModel.getDataMapList().size() > 0 && regions[4] == 0) {
                    // 第五个标记为是否合并
                    list.add(new int[]{start+1, start + exportModel.getDataMapList().size(), regions[2], regions[3]});
                    start += exportModel.getDataMapList().size();
                }

            }
        }
        return list;
    }

    @Override
    public String getExportTitle() {
        return exportModels.get(0).getExportTitle();
    }

    @Override
    public Map<String, String> getExportHeaderAlias() {
        return new LinkedHashMap<>(exportModels.get(0).getExportHeaderAlias());
    }

}
